<?PHP
  class DataValidator{
    private $id        = -1;
    private $name      = "";
    private $regex     = "";
    private $message   = "";
    private $htmlCode  = "";
    private $lastError = "";

    public function __construct($id){
      $id  = DataBase::Current()->EscapeString($id);
      if($obj = DataBase::Current()->ReadRow("SELECT * FROM {'dbprefix'}data_validator WHERE id = '".$id."'")){
        $this->id       = $obj->id;
        $this->name     = $obj->name;
        $this->regex    = $obj->regex;
        $this->message  = $obj->message;
        $this->htmlCode = $obj->htmlCode;
      }
    }

    /**
     *
     * @param string $name
     * @param string $value
     * @return string
     */
    public function getControlCode($name,$value){
      $res = $this->htmlCode;
      $res = str_ireplace("{VAR:NAME}",$name,$res);
      $res = str_ireplace("{VAR:VALUE}",htmlentities($value),$res);
      return $res;
    }

    /**
     *
     * @param string $value
     * @return boolean
     */
    public function validate($value){
      $res = true;
      preg_match($this->regex, $value, $results);
      $res = sizeOf($results) > 0;
      if(!$res){
        $this->lastError = $this->message."<br />";
      }
      return $res;
    }

    /**
     *
     * @return string
     */
    public function getLastError(){
      return $this->lastError;
    }

  }
?>